// pages/healthManage/addManage/index.js
import WxValidate from '../../../utils/validate'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    checkboxItems:[{"category":"Quarter A",checked:false},{"category":"Quarter B",checked:false},{"category":"Quarter C",checked:false},{"category":"Quarter D",checked:false},{"category":"Weekly",checked:false}],
      array3:[],
      tempCategory:[],
      value3:0,
      workcode:[],
      codelist:[],
      winHeight:"",
      now:"",
      workcodeList:[],
      statusName:"",
      item:"",
      workOrderTypeList:['CV','PM'],
      serialOrLotNumber:"",
      description:"",
      workOrderCode:"",
      planTime:"",
      workOrderType:"",
      plan:"",
      endTime:"",
      checkType:"",
      engineer:""
  },
  initValidate() {
    const rules = {
      code:{
        required: true,
      },
      workOrderType:{
        required: true,
      },
      workOrderCode:{
        required: true,
      },


    }
    const messages = {
      code:{
        required: '请填写设备编号',
      },
      workOrderType:{
        required: '请填写工单类型',
      },
      workOrderCode:{
        required: '请填写工单号',
      },
    }
    let that = this;
    this.WxValidate = new WxValidate(rules, messages)
    // this.WxValidate.addMethod('limitInput',(value, param)=>{
    //   return  this.WxValidate.optional(value) || /(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9])/.test(value);
    // },'密码包含大小写英文数字和符号')
  },
    // 展示信息
    showModal(error){
      wx.showModal({
        content: error.msg,
        showCancel: false,
      })
    },
  bindPicker3Change: function(e) {
    this.setData({
        serialOrLotNumber:this.data.array3[e.detail.value],
        description:"",
        workOrderCode:"",
        planTime:"",
        workOrderType:"",
        plan:"",
        endTime:"",
        engineer:""
    })
    this.getOderCode()
    this.getCodeData()
    this.getCheckItem()
  },
  workOrderCodeChange(e){
    let self = this
    this.setData({
      workOrderCode:this.data.codeList[e.detail.value]
  })
  self.data.workcodeList.forEach(e=>{
    if(e.workOrderNumber==self.data.workOrderCode){
      if(e.checkItem){
        self.data.checkboxItems.forEach(a=>{
          if(a.category == e.checkItem){
            a.checked = true
          } else if (
            self.data.workOrderType == "CV" &&
            a.category == "Weekly"
          ) {
            a.checked = true;
          } else {
            a.checked = false;
          }
        })
      }else {
        self.items.forEach((a) => {
          if (self.data.workOrderType == "CV" && a.category == "Weekly") {
            a.checked = true;
          } else {
            a.checked = false;
          }
        });
      }

      self.setData({
        plan:e.plan,
        engineer:e.technicianMemberName,
        endTime:e.due,
        checkboxItems:self.data.checkboxItems,
        description:e.initialReport
      })
    }
  })
  },
  getCheckItem(){
    let self = this
    self
    .axios
    .query("HealthControlCheckItem", {}, { code: self.data.item.code })
    .then(function (response) {
      console.log(response)
      let arr=response.data.rows
      // arr.forEach((e) => {
      //     e.checked = false;
      // });
      let arrtwo = ["Quarter A","Quarter B","Quarter C","Quarter D","Weekly"]
      arr.forEach((e) => {
        if(arrtwo.indexOf(e.category)==-1){
          let obj = {
            ...e,checked:true
          }
            self.data.tempCategory.push(obj)
        }
        e.checked = false;
      });
      self.data.item.relationList.forEach(a=>{
        self.data.checkboxItems.forEach((e) => {
          if(e.category==a.category){
            e.checked = true;
          }
        });
      })

      self.setData({
        checkboxItems:self.data.checkboxItems,
        checkType:arr[0].type
      })
    });
  },
  getCodeData(){
    let self = this
    self
    .axios
    .custom("HealthControlInformation", "getOpenWorkByCode", {
      id: self.data.serialOrLotNumber,
    })
    .then(function (response) {
      self.data.workcodeList = response.data;
      console.log(response);
    });
  },
  getOderCode(){
    let self =this
    let code = self.data.serialOrLotNumber;
    self
      .axios
      .custom("HealthControlInformation", "getOpenWorkByCode", {
        id: code,
      })
      .then(function (response) {
        self.data.workcode = response.data;
        console.log(response);
      });
  },
  planTimeChange: function (e) {
    this.setData({
      planTime: e.detail.value
    })
},
  workOrderTypeChange(e){
    let self =this
    this.setData({
      workOrderType:this.data.workOrderTypeList[e.detail.value]
    })
    if (this.data.workOrderTypeList[e.detail.value] == "CV") {
      let arr=[]
      let arr2=[]
       arr= self.data.workcode.filter((e) => {
        return e.purposeOfVisit == "Customer Visit";
      });
      arr.forEach(e=>{
        arr2.push(e.workOrderNumber)
      })
      console.log(arr)
      self.setData({
        codeList:arr2
      })
    } else if (this.data.workOrderTypeList[e.detail.value]== "PM") {
      let arr=[]
      let arr2=[]
      arr = self.data.workcode.filter((e) => {
        return e.purposeOfVisit == "Preventative Maintenance (PM)";
      });
      arr.forEach(e=>{
        arr2.push(e.workOrderNumber)
      })
      console.log(arr)
      self.setData({
        codeList:arr2
      })
    }
  },
  getequiment(){
    this
    .axios
    .custom("AllInstalledProducts", "serialOrLotNumbers", {
      id: this.Store.getItem("userid"),
    })
    .then((result) => {
      console.log(result);
      this.setData({
        array3:result.data
      })
    })
    .catch((err) => {
      self.$notify(err.data.msg, "error");
    });
  },
  //检查项改变事件
  checkboxChange: function (e) {
    console.log('checkbox发生change事件，携带value值为：', e.detail.value);
    var checkboxItems = this.data.checkboxItems, values = e.detail.value;
    for (var i = 0, lenI = checkboxItems.length; i < lenI; ++i) {
        checkboxItems[i].checked = false;

        for (var j = 0, lenJ = values.length; j < lenJ; ++j) {
            if(checkboxItems[i].category == values[j]){
                checkboxItems[i].checked = true;
                break;
            }
        }
    }
    this.setData({
        checkboxItems: checkboxItems
    });
},
  //保存
    save(){
   
      let self = this
      // self
      // .axios
      // .custom("HealthControlInformation", "judgeCodeTypeByModel", {
      //   id: self.data.serialOrLotNumber,
      // }).then(function(res){
      //   if(res.data=="TOMO"){
      //   }else{
      //   }
      // })
      let response = this.data.checkType
      console.log(this.data.checkType)
    //   if(response=="TOMO"){
    //     for(var i=0;i<self.data.checkboxItems.length;i++){
    //       if(self.data.checkboxItems[i].checked==true&&i>2&&i<7){
    //         this.data.checkboxItems[0].checked = true
    //         this.data.checkboxItems[1].checked = true
    //         this.data.checkboxItems[2].checked = true
    //         break
    //       }
    //     }
    // }else{
    //     for(var a=0;a<self.data.checkboxItems.length;a++){
    //       if(self.data.checkboxItems[a].checked==true&&a>1&&a<6){
    //         this.data.checkboxItems[0].checked = true
    //         this.data.checkboxItems[1].checked = true
    //         break
    //       }

    //     }
    // }
      // if(this.data.checkboxItems.length==8){
      //   for(var i=0;i<this.data.checkboxItems.length;i++){
      //     if(this.data.checkboxItems[i].checked==true&&i>2&&i<7){
      //       this.data.checkboxItems[0].checked = true
      //       this.data.checkboxItems[1].checked = true
      //       this.data.checkboxItems[2].checked = true
      //       break
      //     }
      //   }
      // }else{
      //   for(var i=0;i<this.data.checkboxItems.length;i++){
      //     if(this.data.checkboxItems[i].checked==true&&i>1&&i<6){
      //       this.data.checkboxItems[0].checked = true
      //       this.data.checkboxItems[1].checked = true
      //       break
      //     }
      //   }
      // }
      console.log(this.data.checkboxItems)
      let arr=[]
      let juge = false
      this.data.checkboxItems.forEach((e,index)=>{
        if(e.checked){
          if(index<4){
            juge = true
          }
          arr.push(e)
        }
      })
      if(juge){
        arr = self.data.tempCategory.concat(arr)
      }
      if(arr.length<1){
        wx.showToast({
          title: '请选择检查项',
          icon: 'error',
          duration: 2000,
        })
        return
      }
      console.log(arr)
      let obj={
        code:self.data.serialOrLotNumber,
        description:self.data.description,
        workOrderCode:self.data.workOrderCode,
        planTime:self.data.planTime,
        workOrderType:self.data.workOrderType,
        plan:self.data.plan,
        id:self.data.item.id,
        isCreateReport:self.data.item.isCreateReport,
        status:self.data.item.status,
        endTime:self.data.endTime,
        engineer:self.data.engineer,
        relationList:arr
      }
      if(!this.WxValidate.checkForm(obj)){
        let msg = this.WxValidate.errorList[0];
        this.showModal(msg);
        return false
      }
      self.axios.update("HealthControlInformation",obj, false)
      .then((res)=> {
        if (res.code == '200') {
          wx.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 2000,
            success: () => {
              wx.navigateBack({
                delta: 2
            });
            }
          })
  
        } else {
  
        }
    //     wx.showToast({
    //       title: '保存成功',
    //       icon: 'succes',
    //       duration: 1000,
    //       mask:true
    //   })
    //   wx.navigateBack({
    //     delta: 1
    // })
      })
      .catch(e=>{
      })
    },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let self = this
    let data = new Date()
    let month = data.getMonth()+1
    if((month)<10){
      month="0"+month
    }
    let datatime = data.getDate()
    if(datatime<10){
      datatime = "0"+data
    }
    let time = data.getFullYear()+"-"+month+"-"+datatime
    console.log(time)
    this.setData({
      now:time
    })
    const eventChannel = this.getOpenerEventChannel();
		// 监听 index页面定义的toHome 事件
		eventChannel.on('headlEd', (res) => {
      console.log(res,'页面传值') 
      this.setData({
        item:res.item,
        statusName:res.statusName
      })
      self.getequiment()
      self.initValidate();
      self.getAlldata()
      self.getCheckItem()
    })
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR - 140;
        console.log(calc)
        self.setData({
          winHeight: calc
        });
      }
    });
  },
  getAlldata(){
    let self = this;
    self
      .axios
      .query("HealthControlInformation", {}, { id: self.data.item.id }, "", false)
      .then((res) => {
        console.log(res)
        // if(res.data.rows[0].resultList){
        //   console.log("here1")
        //   res.data.rows[0].resultList.forEach(e=>{
        //     e.result = e.resultRecord
        //   })
        //   self.setData({
        //     allData:res.data.rows[0].resultList,
        //     resultjuge:true
        //   })
        // }else{
        //   self.setData({
        //     resultjuge:false
        //   })
        // }
        console.log("here")
        self.setData({
          serialOrLotNumber:res.data.rows[0].code,
          description:res.data.rows[0].description,
          workOrderCode:res.data.rows[0].workOrderCode,
          planTime:res.data.rows[0].planTime.substring(0,res.data.rows[0].planTime.length-9),
          workOrderType:res.data.rows[0].workOrderType,
          plan:res.data.rows[0].plan,
          endTime:res.data.rows[0].endTime.substring(0,res.data.rows[0].endTime.length-9),
          engineer:res.data.rows[0].engineer,
          status:res.data.rows[0].status,
          id:res.data.rows[0].id,
          dataList:res.data.rows[0].resultList
        })
      }).catch(()=>{
  
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})